<?php

namespace App\Http\Controllers;

use App\Common\Func;
use App\User;
use Illuminate\Http\Request;
use Laravist\GeeCaptcha\GeetestLib;

if (!session_id()){
    session_start();
}

class StudioController extends Controller
{

    /**
     * 登录操作
     */
    public function login(Request $request)
    {
        $challenge = $request->get('challenge');
        $validate = $request->get('validate');
        $seccode = $request->get('seccode');
        $GtSdk = new GeetestLib(env('CAPTCHA_ID'), env('PRIVATE_KEY'));
        $flag = false;
        if ($_SESSION['gtserver'] == 1) {
            $result = $GtSdk->success_validate($challenge, $validate, $seccode);
            $flag = $result;
        } else {
            if ($GtSdk->fail_validate($challenge, $validate, $seccode)) {
                $flag = true;
            }
        }

        if ($flag) {
            $mobile = $request->get('mobile');
            $pwd2 = $request->get('pwd');
            $pwd = substr(md5(env('USER_MD5_KEY', '') . $pwd2), 7, 27);
            $ip = $_SERVER['REMOTE_ADDR'];
            $u = new User();
            $user = $u->do_login($mobile, $pwd, $ip, $pwd2);
            if ($user) {
                $_SESSION['tianqi_userid'] = $user;
                echo json_encode(array('status' => 0, 'info' => '登录成功', 'data' => $user));
            } else {
                echo json_encode(array('status' => 4, 'info' => '用户不存在'));
            }
        } else {
            echo json_encode(array('status' => 3, 'info' => '验证码验证失败'));
        }
        exit;
    }

    /**
     * 获取用户信息
     */
    public function user_data()
    {
        $user = Func::User();
        if ($user) {
            echo json_encode(array('status' => 0, 'data' => $user));
        }else{
            echo json_encode(array('status' => 4, 'info' => '用户信息不存在'));
        }
        exit;
    }

    /**
     * 修改用户信息
     */
    public function update(Request $request)
    {
        $user = Func::User();
        if ($user){
            $params = $request->all();
            $params['id'] = $user['id'];
            $u = new User();
            $res = $u->user_update($params);
            if ($res){
                return array('status'=>0, 'info'=>'修改成功');
            }else{
                return array('status'=>4, 'info'=>'修改失败');
            }
        }else{
            return array('status'=>1, 'info'=>'登录超时');
        }
    }

    /**
     * 保存头像
     */
    public function save_photo(Request $request)
    {
        $params = $request->all();
        $user = Func::User();
        $params['id'] = $user['id'];
        $u = new User();
        $res = $u->user_update($params);
        if ($res){
            return array('status'=>0, 'info'=>'修改成功');
        }else{
            return array('status'=>4, 'info'=>'修改失败');
        }
    }

    /**
     * 获取验证码
     */
    public function get_code(Request $request)
    {
        $mobile = $request->get('mobile');
        if (preg_match('/^1([3|5|7|8])\d{9}$/', $mobile)) {
            $code = rand(100000, 999999);
            $u = new User();
            $res = $u->create_code($mobile, $code);
            if ($res == 200) {
                echo json_encode(array('status' => 0, 'info' => $code));
                //$stat = $this->send_sms($mobile, $code);
                /*$stat = Func::send_sms($mobile, $code);
                if ($stat) {
                    echo json_encode(array('status' => 0, 'info' => "验证码已发送到$mobile"));
                }else{
                    echo json_encode(array('status' => 4, 'info' => "短信发送失败，请重试"));
                }*/
            } elseif ($res == 1) {
                echo json_encode(array('status' => 3, 'info' => '此手机号已注册'));
            } elseif ($res == 2) {
                echo json_encode(array('status' => 2, 'info' => '验证码获取失败'));
            }
        } else {
            echo json_encode(array('status' => 1, 'info' => '手机号不合法'));
        }
        exit;
    }

    /**
     * 注册第一步验证手机是否合法
     */
    public function reg(Request $request)
    {
        $mobile = $request->get('mobile');
        $code = $request->get('code');
        $u = new User();
        $res = $u->verify_code($mobile, $code);
        if ($res){
            $res = json_decode(json_encode($res), true);
            $now = strtotime(date('Y-m-d H:i:s'));
            $ago = strtotime($res['created_at']);
            setcookie('tianqi_mobile', $mobile, 300);
            if (($now - $ago) / 60 < 5) {
                echo json_encode(array('status' => 0, 'info' => '成功'));
            }else{
                echo json_encode(array('status' => 3, 'info' => '验证码已失效'));
            }
        }else{
            echo json_encode(array('status'=>4,'info'=>'验证码错误'));
        }
        exit;
    }

    /**
     * 注册第二步，保存用户注册信息
     */
    public function reg_info(Request $request)
    {
        $params = $request->all();
        $pwd = $params['pwd'];
        $pwd = substr(md5(env('USER_MD5_KEY').$pwd),7,27);
        $params['pwd'] = $pwd;
        if (!empty($_COOKIE['tianqi_mobile'])){
            $params['mobile'] = $_COOKIE['tianqi_mobile'];
        }
        $u = new User();
        $res = $u->register($params);
        if ($res){
            $_SESSION['tianqi_userid'] = $res;
            echo json_encode(array('status'=>0, 'info'=>'注册成功'));
        }else{
            echo json_encode(array('status'=>0, 'info'=>'注册失败'));
        }
    }

    /**
     * 向用户手机发送验证码
     */
    private function send_sms($mobile,$code) {
        $url = 'http://www.sendcloud.net/smsapi/send';

        $param = array(
            'smsUser' => '***',
            'templateId' => '1',
            'phone' => $mobile,
            'vars' => "{\"%code%\":\"$code\"}"
        );

        $sParamStr = "";
        ksort($param);
        foreach ($param as $sKey => $sValue) {
            $sParamStr .= $sKey . '=' . $sValue . '&';
        }

        $sParamStr = trim($sParamStr, '&');
        $smskey = '***';
        $sSignature = md5($smskey."&".$sParamStr."&".$smskey);


        $param = array(
            'smsUser' => '***',
            'templateId' => '1',
            'phone' => $mobile,
            'vars' => "{\"%code%\":\"$code\"}",
            'signature' => $sSignature
        );

        $data = http_build_query($param);
        //echo $data;

        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type:application/x-www-form-urlencoded',
                'content' => $data
            ));
        $context  = stream_context_create($options);
        $result = file_get_contents($url, FILE_TEXT, $context);
        return $result;
    }

}
